package com.gxa.eshop.portal.interceptor;

import com.gxa.eshop.common.Result;
import com.gxa.eshop.pojo.User;
import com.gxa.eshop.portal.thread.UserThreadLocal;


import com.gxa.eshop.utils.JsonUtils;
import com.gxa.eshop.utils.ResponseUtils;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author bill
 * @date 2022/1/20 11:26
 */
public class LoginInterceptor implements HandlerInterceptor {

//    @Reference
//    private UserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            Result result = new Result(500010, "没有登录!");
            ResponseUtils.responseJson(response, JsonUtils.objectToJson(result));
            return false;
        }

//        User user = userService.queryUserByToken(token);
//        if(user==null){
//            Result result = new Result(500010, "没有登录!");
//            ResponseUtils.responseJson(response,JsonUtils.objectToJson(result));
//            return false;
//        }

        //绑定用户到当前线程
        //因为service是使用dubbo远程调用，都不在一个项目，更不要说一个线程了，所以使用传统
        //方法无法向service隐式传参
        // 模拟一个登录后的User对象
        User user = new User();
        user.setId(1L);
        user.setUsername("张三丰");
        UserThreadLocal.set(user);

        //dubbo隐式传参
        RpcContext.getContext().setAttachment("userId",user.getId()+"");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        //移除当前线程的用户
        //  UserThreadLocal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}